# -*- coding: utf-8 -*- 
"""
Created by lpf on 2016/11/3 14:22:28.
@author: 李鹏飞
备份数据库
"""
from __future__ import absolute_import
from __future__ import unicode_literals

import logging
import os
import time

from auction import settings
from auction.apps.common import start_scheduler

logger = logging.getLogger(__name__)


def backup_timer():
    """定时器"""
    backup_database()
    scheduler = start_scheduler.scheduler
    # 加定时2点备份数据库
    j = scheduler.add_job(backup_database, 'cron', hour=2, id="backup_database_2am", replace_existing=True)
    logger.debug(j)
    logger.info("加定时器每天2点备份数据库")


def backup_database():
    """备份数据库操作"""
    try:
        DATABASES = settings.DATABASES
        database = DATABASES['default']['NAME']
        username = DATABASES['default']['USER']
        password = DATABASES['default']['PASSWORD']
        # mysql安装的bin目录
        cmd_path = 'cd /d ' + settings.MYSQL_PATH
        # 名字的格式以时间方式命名，方便理解和容易知道时间
        name = time.strftime("%Y-%m-%d-%H%M%S")
        # 存放备份文件的位置
        destDir = settings.MYSQL_BACKUP_PATH
        # 判断文件夹是否存在，不存在则创建
        os.system('if not exist "' + destDir + '" md "' + destDir + '"')
        # 备份的系统命令
        cmd = cmd_path + '&&mysqldump -u' + username + ' -p' + password + ' ' + database + ' > ' + destDir + name + \
              '.sql'
        # 执行系统命令
        os.system(cmd)
        logger.info('备份数据库成功...')
    except Exception as e:
        logger.exception(e)
